import unittest
import os
import sys

def load_all_tests():
    loader = unittest.TestLoader()
    suite = unittest.TestSuite()
    for root, dirs, files in os.walk(os.path.join(os.path.dirname(__file__))):
        for file in files:
            if file.startswith('test') and file.endswith('.py') and file != 'run_all_tests_with_report.py':
                rel_path = os.path.relpath(os.path.join(root, file), os.path.dirname(__file__))
                module_name = rel_path.replace(os.sep, '.')[:-3]
                try:
                    module = __import__(module_name, fromlist=[''])
                    suite.addTests(loader.loadTestsFromModule(module))
                except Exception as e:
                    print(f'加载 {module_name} 失败: {e}')
    return suite

if __name__ == '__main__':
    report_path = os.path.join(os.path.dirname(__file__), '../test_docs/测试报告/test_error_report.txt')
    os.makedirs(os.path.dirname(report_path), exist_ok=True)
    with open(report_path, 'w', encoding='utf-8') as f:
        runner = unittest.TextTestRunner(stream=f, verbosity=2)
        all_tests = load_all_tests()
        result = runner.run(all_tests)
        if not result.wasSuccessful():
            print(f'测试有失败，详细报错信息已保存到: {report_path}')
        else:
            print('所有测试均通过，无错误信息。')
